﻿using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Extension;
using SHZY.Common.Filter;
using SHZY.Common.Models;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Business.Entitys;
using SHZY.Business.Interfaces;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using SHZY.Systems.Entitys.Permission;
using crypto;
using SHZY.Business.Entitys.Dto.QmsBusiIpqcinspectionitemdefect;

namespace SHZY.Business;

/// <summary>
/// 业务实现：缺陷记录.
/// </summary>
[ApiDescriptionSettings(Tag = "Business", Name = "IpqcInspectionitemdefect", Order = 200)]
[Route("api/Business/[controller]")]
public class QmsBusiIpqcinspectionitemdefectService : IQmsBusiIpqcinspectionitemdefectService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<QmsBusiIpqcinspectionitemdefectEntity> _repository;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="QmsBusiIpqcinspectionitemdefectService"/>类型的新实例.
    /// </summary>
    public QmsBusiIpqcinspectionitemdefectService(
        ISqlSugarRepository<QmsBusiIpqcinspectionitemdefectEntity> qmsBusiIpqcinspectionitemdefectRepository,
        ISqlSugarClient context,
        IUserManager userManager)
    {
        _repository = qmsBusiIpqcinspectionitemdefectRepository;
        _userManager = userManager;
    }

    /// <summary>
    /// 获取缺陷记录.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<QmsBusiIpqcinspectionitemdefectInfoOutput>();
    }

    /// <summary>
    /// 获取缺陷记录列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] QmsBusiIpqcinspectionitemdefectListQueryInput input)
    {
        var data = await _repository.Context.Queryable<QmsBusiIpqcinspectionitemdefectEntity,UserEntity>((a,b)=> new JoinQueryInfos(JoinType.Left, a.CreatorUserId == b.Id))
            .Where((a, b) => a.InspectionItem == input.inspectionItem && a.Number == SqlFunc.ToInt32(input.number) && a.DeleteMark == null && a.EnabledMark == 1)
            .Select("a.F_Id,a.F_InspectionItem,a.F_Number,a.F_Defect,a.F_DefectName,a.F_DefectQty,a.F_Severity,a.F_FileInfo,a.F_Remark,b.F_RealName as F_CreatorUserId,a.F_CreatorTime")
            .OrderBy(a => a.CreatorTime, OrderByType.Desc).ToListAsync();
        return new { list = data.Adapt<List<QmsBusiIpqcinspectionitemdefectInfoOutput>>() };
    }

    /// <summary>
    /// 新建缺陷记录.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] QmsBusiIpqcinspectionitemdefectCrInput input)
    {

        if (await _repository.AnyAsync(x => x.InspectionItem == input.inspectionItem && x.Number == SqlFunc.ToInt32(input.number) && x.Defect==input.defect && x.DeleteMark == null))
            throw Oops.Oh("请勿重复添加当前缺陷");
        var entity = input.Adapt<QmsBusiIpqcinspectionitemdefectEntity>();
        var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
        if (isOk < 1)
            throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 删除缺陷记录.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Updateable<QmsBusiIpqcinspectionitemdefectEntity>().SetColumns(it => new QmsBusiIpqcinspectionitemdefectEntity()
        {
            DeleteTime = DateTime.Now,
            DeleteMark = 1,
            DeleteUserId = _userManager.UserId
        }).Where(x => x.Id == id).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1002);
    }
}